package com.cloud.cloudBatis.session.impl;

import com.cloud.cloudBatis.session.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Collection;

public class MapperProxy implements InvocationHandler {
    private SqlSession sqlSession;
    public MapperProxy(SqlSession sqlSession) {
        super();
        this.sqlSession = sqlSession;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String statement = method.getDeclaringClass().getName() + "." + method.getName();
        Class<?> clazz = method.getReturnType();
        if (Collection.class.isAssignableFrom(clazz)) {
            if (args == null) {
                return sqlSession.selectList(statement, null);
            } else {
                return sqlSession.selectList(statement, args[0]);
            }
        } else {
            if (args == null) {
                return sqlSession.selectOne(statement, null);
            } else {
                return sqlSession.selectOne(statement, args[0]);
            }
        }
    }
}
